package com.bosssoft.cloud.wechat.infrastructure.aspect;

import com.bosssoft.cloud.wechat.infrastructure.util.ParamUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局AOP切面
 * <p>
 * 主要做全局日志，入参校验
 *
 * @author wcy create on 2021/6/22 14:49 下午
 */
@Slf4j
@Component
@Aspect
@Order(0)
public class GlobalControllerAspect {

    //为了记录执行时间，方便调试（可选）
    private final ThreadLocal<Long> startTime = new ThreadLocal<>();

    /*
    execution(public * com.bosssoft.cloud.wechat.core.controller.*.*(..)) " +
            "|| execution(public * com.bosssoft.cloud.wechat.common.controller.*.*(..))
     */
    // 定义一个切入点
    // 此处匹配方法为RequestMapping注解的类所属的所有方法，如有特殊需求，可换成上面匹配方法执行等方式
    @Pointcut("@within(org.springframework.web.bind.annotation.RequestMapping)")
    public void pointCut() {
    }

    /**
     * 在进入方法前执行 可以对参数进行限制或者拦截
     * 通常在这边做日志存储存到数据库中(log)
     *
     * @param joinPoint 切点
     */
    @Before("pointCut()")
    public void before(JoinPoint joinPoint) {
        log.info("==================前置执行=====================>");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        MethodSignature ms = (MethodSignature) joinPoint.getSignature();
        HttpServletRequest request = attributes.getRequest();
        log.info("请求来源：" + request.getRemoteAddr());
        log.info("请求URL：" + request.getRequestURL().toString());
        log.info("请求方式：" + request.getMethod());
        log.info("响应方法：" + ms.getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("请求参数：" + paramToString(ms.getParameterNames(), joinPoint.getArgs()));
        log.info("==================前置执行完成==================>");
        startTime.set(System.currentTimeMillis());
        log.info("入参校验...");
        for (Object arg : joinPoint.getArgs())
            ParamUtil.checkParam(arg); // Param参数校验
        log.info("入参校验结束.");
    }

    /**
     * 环绕执行
     * 定义需要匹配的切点表达式，同时需要匹配参数
     *
     * @param pjp pjp
     * @return pjp.proceed()
     * @throws Throwable throw
     */
    @Around("pointCut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        // 往下执行方法
        return pjp.proceed();
    }

    /**
     * 在方法执行后执行
     *
     * @param point 切点
     */
    @After("pointCut()")
    public void after(JoinPoint point) {
        if (startTime.get() == null)
            startTime.set(System.currentTimeMillis());
        log.info("耗时（毫秒）：" + (System.currentTimeMillis() - startTime.get()));
        log.info("==================后置执行==================>");
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "pointCut()", returning = "res")
    public void AfterReturning(JoinPoint joinPoint, Object res) {
        log.info("返回数据：{}", res == null ? "null" : res.toString());
        log.info("==================后置执行完成==================>");
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "pointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        String detail = e.getMessage();
        if (detail == null) detail = "";
        log.error("异常信息：{} {}", e.toString(), detail);
        log.info("==================出现异常==================>");
    }

    /**
     * param=>String
     *
     * @param name param name
     * @param args param args
     * @return string(log)
     */
    private static String paramToString(String[] name, Object[] args) {
        StringBuilder sb = new StringBuilder().append("{");
        for (int i = 0; i < name.length; i++)
            sb.append("\"").append(name[i]).append("\"")
                    .append(":")
                    .append("\"").append(args[i]).append("\"")
                    .append(",");
        return sb.deleteCharAt(sb.length() - 1).append("}").toString();
    }
}
